<template>
    <!-- 整体容器：使用 flex 横向布局 -->
    <div class="goods-layout">
        <!-- 使用 el-container 构建主布局 -->
        <el-container>
            <el-header style="padding: 0; border-bottom: 1px solid #e8e8e8;">
                <div class="header-toolbar">
                    <el-form :model="searchForm" label-width="auto" class="search-form">
                        <el-input v-model="searchForm.keyword" placeholder="商品名称/商品编号/供应商名称查询" />
                        <el-select v-model="searchForm.status" placeholder="显示启用类别" style="width: 100px;">
                            <el-option label="全部" :value="-1" />
                            <el-option label="启用" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                        <el-button type="primary" @click="searchGoods">查询</el-button>
                    </el-form>

                    <div class="action-buttons">
                        <el-button type="primary" @click="AddGoods">新增</el-button>
                        <el-button @click="batchClose">禁用</el-button>
                        <el-button @click="batchOpen">启用</el-button>
                        <el-button>导入</el-button>
                        <el-button>导出</el-button>
                        <el-button @click="batchDelete">删除</el-button>
                    </div>
                </div>
            </el-header>
            <!-- 主内容区（含 header + 表格 + 分页） -->
            <el-container class="main-container">

                <!-- 内容主体：分类提示栏 + 表格 + 分页 -->
                <el-main class="table-main">
                    <!-- 分类提示栏 -->
                    <div class="category-bar">
                        当前分类：{{ selectTypeName }}
                        <el-icon class="toggle-icon" @click="toggleAside">
                            <DArrowRight v-if="!asideCollapsed" />
                            <DArrowLeft v-else />
                        </el-icon>
                    </div>
                    <div class="table-wrapper">
                        <el-table :data="goodsList" style="width: 100%" :row-class-name="tableRowClassName"
                            height="100%" v-loading="tableLoad" border @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55px">
                            </el-table-column>
                            <el-table-column label="序号" type="index" width="50" />
                            <el-table-column label="操作" width="180">
                                <template #default="{ row }">
                                    <el-button size="small" @click="toEdit(row.id)">
                                        <el-icon>
                                            <Edit />
                                        </el-icon>
                                    </el-button>
                                    <el-button size="small" @click="deleteGoods(row.id)">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </el-button>
                                </template>
                            </el-table-column>

                            <el-table-column prop="code" label="商品编号" width="180" />
                            <el-table-column prop="picture" label="图片" width="180">
                                <template #default="scope">
                                    <el-image style="width: 50px; height: 50px" :src="imgStr + scope.row.picture"
                                        preview-teleported :preview-src-list="[imgStr + scope.row.picture]"
                                        fit="cover" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" label="商品名称" width="180" />
                            <el-table-column prop="typeName" label="商品类别" width="180" />
                            <el-table-column prop="specification" label="规格型号" width="180" />
                            <el-table-column prop="defaultSupplierInfo" label="默认供应商" width="180" />
                            <el-table-column prop="brandName" label="品牌" width="180" />
                            <el-table-column prop="unitName" label="单位" width="180" />
                            <el-table-column prop="warehouseName" label="首选仓库" width="180" />
                            <el-table-column prop="stock" label="当前库存" width="180" />
                            <el-table-column prop="initQuantity" label="期初数量" width="180" />
                            <el-table-column prop="cost" label="单价成本" width="180" />
                            <el-table-column prop="initPrice" label="期初总价" width="180" />
                            <el-table-column prop="predictPrice" label="预计采购价" width="180" />
                            <el-table-column prop="purchasePrice" label="最高采购价" width="180" />
                            <el-table-column prop="salePrice" label="最低销售价" width="180" />
                            <el-table-column prop="retailPrice" label="零售价" width="180" />
                            <el-table-column prop="wholesalePrice" label="批发价" width="180" />
                            <el-table-column prop="vipPrice" label="VIP会员价" width="180" />
                            <el-table-column prop="taxRate" label="商品税率" width="180" />
                            <el-table-column prop="discountRate" label="折扣率" width="180" />
                            <el-table-column prop="defaultPrice" label="默认价格" width="180" />
                            <el-table-column prop="createDate" label="创建时间" width="180" />
                            <el-table-column prop="remark" label="备注" width="180" />

                            <el-table-column prop="status" label="状态" width="180">
                                <template #default="{ row }">
                                    <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
                                        @change="() => handleStatusChange(row)" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 分页 -->
                    <div class="pagination-container">
                        <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
                            :page-sizes="[5, 10, 15, 20]" :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </el-main>
                <!-- 侧边分类树（可折叠） -->
                <el-aside v-show="!asideCollapsed" width="250px" class="goods-aside">
                    <el-card>
                        <template #header>
                            <el-input v-model="typeFilter" placeholder="请输入类别名称" suffix-icon="Search" clearable />
                        </template>
                        <el-tree ref="treeRef" :data="treeSelectData"
                            :props="{ value: 'id', label: 'name', children: 'children' }" default-expand-all
                            node-key="id" @node-click="handleNodeClick" :filter-node-method="filterTreeNode">
                            <template #default="{ data }">
                                <span>
                                    <el-icon>
                                        <Folder v-if="data.children && data.children.length > 0" />
                                        <Document v-else />
                                    </el-icon>
                                    {{ data.name }}
                                </span>
                            </template>
                        </el-tree>
                    </el-card>
                </el-aside>
            </el-container>
        </el-container>
    </div>
</template>

<script setup>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { onMounted, reactive, ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import imgStr from '@/store/imgStr';

const router = useRouter();
// 表格加载状态
const tableLoad = ref(false)

// 搜索表单
const searchForm = ref({
    keyword: '',
    type: null,
    status: 1,
})

const pageInfo = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

// 新增响应式变量
const asideCollapsed = ref(false)


const treeRef = ref()
const typeFilter = ref('') // 树搜索用（可选）

// 选中的类别名称
const selectTypeName = ref('全部')

// 切换侧边栏
const toggleAside = () => {
    asideCollapsed.value = !asideCollapsed.value
}

// 搜索
const searchGoods = () => {
    getGoodsList()
}

// 商品列表
const goodsList = ref([])
// 获取商品分页
const getGoodsList = async () => {
    tableLoad.value = true

    try {

        searchForm.value.status = searchForm.value.status == '-1' ? null : searchForm.value.status

        const res = await axios.get('/api/basic/goods/goodsByPage', {
            params: {
                pageNum: pageInfo.pageNum,
                pageSize: pageInfo.pageSize,
                ...searchForm.value
            }
        })

        if (res.data.code === 5200) {
            goodsList.value = res.data.pageInfo.list
            pageInfo.total = res.data.pageInfo.total
            pageInfo.pageNum = res.data.pageInfo.pageNum
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch {
        ElMessage.error('获取商品分页出错')
    } finally {
        tableLoad.value = false
    }
}

const goodsType = ref([])

const getGoodsType = async () => {
    const params = {
        name: searchForm.value.name,
    }

    try {
        const res = await axios.get('/api/basic/goods/allGoodsType', { params })

        if (res.data.code === 5200) {
            goodsType.value = res.data.goodsTypeList
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

const treeData = computed(() => {
    const roots = []
    const map = {}
    goodsType.value.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    goodsType.value.forEach(item => {
        if (item.parentId === null || item.parentId === '0') {
            roots.push(map[item.id])
        } else {
            const parentObj = map[item.parentId]
            if (parentObj) {
                parentObj.children.push(map[item.id])
            }
        }
    })
    return roots
})

const treeSelectData = computed(() => {
    const enabledTreeData = treeData.value
    return [
        {
            id: '0',
            name: '全部',
            children: enabledTreeData
        }
    ]
})

// 在 setup 内部
watch(typeFilter, (val) => {
    treeRef.value?.filter(val)
})

const filterTreeNode = (value, data) => {
    if (!value) return true
    return data.name.includes(value)
}

const handleSizeChange = (val) => {
    pageInfo.pageSize = val
    pageInfo.pageNum = 1
    getGoodsList()
}

const handleCurrentChange = (val) => {
    pageInfo.pageNum = val
    getGoodsList()
}

// 新增商品跳转方法
const AddGoods = () => {
    router.push({ name: 'addGoodsComponent' });
};


const tableRowClassName = ({ rowIndex }) => {
    return {
        'table-row-even': rowIndex % 2 === 0,
        'table-row-odd': rowIndex % 2 !== 0
    };
};

// 选中类别
const handleNodeClick = (nodeData) => {
    searchForm.value.type = nodeData.id === 0 ? null : nodeData.id
    pageInfo.pageNum = 1
    selectTypeName.value = nodeData.name
    getGoodsList()
}

// 切换状态
const handleStatusChange = async (row) => {
    tableLoad.value = true
    const originalStatus = row.status
    try {
        const res = await axios.post('/api/basic/goods/updateGoodsStatus', null, {
            params: {
                id: row.id,
                status: originalStatus === 1 ? 0 : 1
            }
        })
        if (res.data.code === 5200) {
            ElMessage.success('状态更新成功')
            await getGoodsList()
        } else {
            ElMessage.error('状态更新失败')
        }
    } catch (error) {
        ElMessage.error('网络错误，请重试')
    } finally {
        tableLoad.value = false
    }
}

// 选中的表格对象
const selections = ref([])

const selectionIds = computed(() => selections.value.map(item => item.id))

// 选中多选框
const handleSelectionChange = (selection) => {
    selections.value = selection
}

// 批量禁用
const batchClose = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {

    const params = {
        ids: selectionIds.value,
        status
    }

    try {
        const res = await axios.post("/api/basic/goods/batchUpdateGoodsStatus", params)
        if (res.data.code === 5200) {
            ElMessage.success("修改成功")
            await getGoodsList()
        } else {
            ElMessage.error("修改失败")
        }
    } catch (error) {
        ElMessage.error("修改失败")
    }
}

const toEdit = (id) => {
  router.push({
    name: 'addGoodsComponent', 
    query: { id }
  });
};

// 删除
const deleteGoods = async (id) => {
    try {
        const res = await axios.post("/api/basic/goods/deleteGoods", null, { params: { id } })
        if (res.data.code === 5200) {
            ElMessage.success("删除成功")
            await getGoodsList()
        } else {
            ElMessage.error("删除失败")
        }
    } catch (error) {
        ElMessage.error("删除失败")
    }
}


// 批量删除
const batchDelete = async () => {
    try {
        const res = await axios.post("/api/basic/goods/batchDeleteGoods", selectionIds.value)
        if (res.data.code === 5200) {
            ElMessage.success("删除成功")
            await getGoodsList()
        } else {
            ElMessage.error("删除失败")
        }
    } catch (error) {
        ElMessage.error("删除失败")
    }
}


onMounted(() => {
    getGoodsList()
    getGoodsType()
})

</script>

<style scoped>
.goods-layout {
    height: calc(100vh - 60px);
    padding: 16px;
    box-sizing: border-box;
}

/* el-container 默认是 flex，我们让它占满 */
:deep(.el-container) {
    height: 100%;
}

.main-container {
    flex: 1;
    display: flex;
    flex-direction: row;
    /* 改为水平布局 */
    overflow: hidden;
}

.header-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
}

.search-form {
    display: flex;
    gap: 12px;
    align-items: center;
}

.search-form .el-input,
.search-form .el-select {
    width: auto;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.table-main {
    padding: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    flex: 1;
    /* 占据剩余空间 */
}

.category-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    background-color: #eeeeee;
    padding: 0 16px;
    font-size: 14px;
}

.toggle-icon {
    cursor: pointer;
    font-size: 18px;
    color: #606266;
}

.table-wrapper {
    flex: 1;
    overflow: auto;
    margin-top: 8px;
    border: 1px solid #e8e8e8;
}

/* 表头固定 */
:deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
}

:deep(.table-row-even) {
    background-color: #f9f9f9;
}

:deep(.table-row-odd) {
    background-color: #fff;
}

.goods-aside {
    flex-shrink: 0;
    width: 250px;
    overflow: auto;
    height: 100%;
    display: flex;
    /* 添加此属性 */
    flex-direction: column;
    /* 添加此属性 */
}

/* 为 el-card 添加样式以占满父容器高度 */
.goods-aside :deep(.el-card) {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
}

/* 为 el-card__body 添加样式以正确处理内部内容 */
.goods-aside :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: auto;
}

/* 确保 el-tree 占满卡片内容区域 */
.goods-aside :deep(.el-tree) {
    flex: 1;
    overflow: auto;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
}
</style>
